// const { RigidbodySchema } = require("XrFrame/components");
import Dialog from '@vant/weapp/dialog/dialog';
// pages/record/record.js
var charts = new Array();
Page({
  data: {
    index: 0,
    selectColor1: {
      '0%': '#00d200', // 稍微暗一点的绿色
      '100%': '#003900' // 稍微暗一点的深绿色
    },
    selectColor2: {
      '0%': '#FFA500', // 橙色
      '100%': '#FF8C00' // 深橙色
    },
    selectColor3: {
      '0%': '#ff3333', // 调亮后的鲜红色
      '100%': '#D32F2F' // 调亮后的深红色
    },

    chartData: {},
    chartData2: {},
    chartData4: {},
    chartDataEmotion: {},
    stress: 0,
    account_id: 0,
    //日期选择对象
    date: '2024-03-10',
    stressarray: [
      //{
      //   stress: 0,
      //   date: '2024-04-01',
      // }, {
      //   stress: 80,
      //   date: '2024-04-26',
      // }, {
      //   stress: 50,
      //   date: '2024-05-11',
      //}
    ],
    //这里的 opts 是图表类型 type="radar" 的全部配置参数，您可以将此配置复制到 config-ucharts.js 文件中下标为 ['radar'] 的节点中来覆盖全局默认参数。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
    opts: {
      timing: "easeOut",
      duration: 1000,
      rotate: false,
      rotateLock: false,
      color: ["#0F40F5", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"], //调图表颜色
      padding: [5, 5, 5, 5],
      fontSize: 12, //字体大小
      fontColor: "#666666",
      dataLabel: false,
      dataPointShape: false,
      dataPointShapeType: "hollow",
      touchMoveLimit: 60,
      enableScroll: false,
      enableMarkLine: false,
      legend: {
        show: false, //不展示标签名
        position: "right",
        lineHeight: 25,
        float: "center",
        padding: 5,
        margin: 5,
        backgroundColor: "rgba(0,0,0,0)",
        borderColor: "rgba(0,0,0,0)",
        borderWidth: 0,
        fontSize: 13,
        fontColor: "#666666",
        hiddenColor: "#CECECE",
        itemGap: 10,
        areaStyle: {
          color: "#003366", // 设置面的颜色为蓝紫色
          opacity: 1 // 设置面的透明度为 0.5
        },
        area: true // 确保显示填充区域
      },
      extra: {
        radar: {
          gridType: "radar",
          gridColor: "#B5C4D0", //网线的颜色
          gridCount: 3,
          opacity: 0.8,
          max: 6,
          labelShow: true,
          gridEval: 1,
          radius: 55,
          axisLabel: false,
          axisLabelTofix: 0,
          labelColor: "black", //字的颜色
          labelPointShow: false,
          labelPointRadius: 3,
          labelPointColor: "#CCCCCC",
          border: false,
          borderWidth: 2,
          linearType: "none"
        },
        tooltip: {
          showBox: true,
          showArrow: true,
          showCategory: false,
          borderWidth: 0,
          borderRadius: 0,
          borderColor: "#000000",
          borderOpacity: 0.7,
          bgColor: "#000000",
          bgOpacity: 0.7,
          gridType: "solid",
          dashLength: 4,
          gridColor: "#CCCCCC",
          boxPadding: 3,
          fontSize: 10,
          lineHeight: 20,
          fontColor: "#00008B",
          legendShow: true,
          legendShape: "auto",
          splitLine: true,
          horizentalLine: false,
          xAxisLabel: false,
          yAxisLabel: false,
          labelBgColor: "#FFFFFF",
          labelBgOpacity: 0.7,
          labelFontColor: "#666666"
        }
      }
    },
    opts2: {
      timing: "easeOut",
      duration: 1000,
      rotate: false,
      rotateLock: false,
      color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
      padding: [15, 10, 0, 15],
      fontSize: 13,
      fontColor: "#666666",
      dataLabel: false, //每一点的值
      dataPointShape: true,
      dataPointShapeType: "solid",
      touchMoveLimit: 60,
      enableScroll: false,
      enableMarkLine: false,
      legend: {
        show: false,
        position: "bottom",
        float: "center",
        padding: 5,
        margin: 5,
        backgroundColor: "rgba(0,0,0,0)",
        borderColor: "rgba(0,0,0,0)",
        borderWidth: 0,
        fontSize: 13,
        fontColor: "#666666",
        lineHeight: 11,
        hiddenColor: "#CECECE",
        itemGap: 10
      },
      xAxis: {
        disableGrid: true,
        disabled: false,
        axisLine: true,
        axisLineColor: "#CCCCCC",
        calibration: false,
        fontColor: "#666666",
        fontSize: 13,
        lineHeight: 20,
        marginTop: 0,
        rotateLabel: false,
        rotateAngle: 45,
        itemCount: 5,
        boundaryGap: "center",
        splitNumber: 5,
        gridColor: "#CCCCCC",
        gridType: "solid",
        dashLength: 4,
        gridEval: 1,
        scrollShow: false,
        scrollAlign: "left",
        scrollColor: "#A6A6A6",
        scrollBackgroundColor: "#EFEBEF",
        title: "",
        titleFontSize: 13,
        titleOffsetY: 0,
        titleOffsetX: 0,
        titleFontColor: "#666666",
        format: ""
      },
      yAxis: {
        gridType: "dash",
        dashLength: 2,
        disabled: false,
        disableGrid: false,
        splitNumber: 5,
        gridColor: "#CCCCCC",
        padding: 1,
        showTitle: false,
        data: []
      },
      extra: {
        line: {
          type: "straight",
          width: 2,
          activeType: "hollow",
          linearType: "none",
          onShadow: false,
          animation: "vertical"
        },
        tooltip: {
          showBox: true,
          showArrow: true,
          showCategory: false,
          borderWidth: 0,
          borderRadius: 0,
          borderColor: "#000000",
          borderOpacity: 0.7,
          bgColor: "#000000",
          bgOpacity: 0.7,
          gridType: "solid",
          dashLength: 4,
          gridColor: "#CCCCCC",
          boxPadding: 3,
          fontSize: 13,
          lineHeight: 20,
          fontColor: "#FFFFFF",
          legendShow: true,
          legendShape: "auto",
          splitLine: true,
          horizentalLine: false,
          xAxisLabel: false,
          yAxisLabel: false,
          labelBgColor: "#FFFFFF",
          labelBgOpacity: 0.7,
          labelFontColor: "#666666"
        },
        markLine: {
          type: "solid",
          dashLength: 4,
          data: []
        }
      }
    },
    opts3: {

      timing: "easeOut",
      duration: 1000,
      rotate: false,
      rotateLock: false,
      color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
      padding: [0, 0, 0, 0],
      fontSize: 10, //改字体大小
      fontColor: "#666666",
      dataLabel: true,
      dataPointShape: true,
      dataPointShapeType: "solid",
      touchMoveLimit: 60,
      enableScroll: false,
      enableMarkLine: false,
      legend: {
        show: false,
        position: "left",
        lineHeight: 25,
        float: "center",
        padding: 0,
        margin: 0,
        backgroundColor: "rgba(0,0,0,0)",
        borderColor: "rgba(0,0,0,0)",
        borderWidth: 0,
        fontSize: 13,
        fontColor: "#666666",
        hiddenColor: "#CECECE",
        itemGap: 10
      },
      extra: {
        rose: {
          type: "area",
          minRadius: 30,
          activeOpacity: 0.5,
          activeRadius: 10,
          offsetAngle: 0,
          labelWidth: 5,
          border: false,
          borderWidth: 2,
          borderColor: "#FFFFFF",
          linearType: "none"
        },
        tooltip: {
          showBox: true,
          showArrow: true,
          showCategory: true,
          borderWidth: 0,
          borderRadius: 0,
          borderColor: "#000000",
          borderOpacity: 0.7,
          bgColor: "#000000",
          bgOpacity: 0.7,
          gridType: "solid",
          dashLength: 4,
          gridColor: "#CCCCCC",
          boxPadding: 3,
          fontSize: 13,
          lineHeight: 5,
          fontColor: "#FFFFFF",
          legendShow: true,
          legendShape: "auto",
          splitLine: true,
          horizentalLine: false,
          xAxisLabel: false,
          yAxisLabel: false,
          labelBgColor: "#FFFFFF",
          labelBgOpacity: 0.7,
          labelFontColor: "#666666"
        }
      }
    },
    opts4: {
      timing: "easeOut",
      duration: 1000,
      rotate: false,
      rotateLock: false,
      color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
      padding: [15,11,0,15], //画布填充边距[上,右,下,左]，Array格式
      fontSize: 13,
      fontColor: "#666666",
      dataLabel: false, //不显示上面标的数字
      dataPointShape: true,
      dataPointShapeType: "solid",
      touchMoveLimit: 60,
      enableScroll: false,
      enableMarkLine: false,
      legend: {
        show: true,
        position: "right",
        float: "center",
        padding: 5,
        margin: 5,
        backgroundColor: "rgba(0,0,0,0)",
        borderColor: "rgba(0,0,0,0)",
        borderWidth: 0,
        fontSize: 13,
        fontColor: "#666666",
        lineHeight: 16,
        hiddenColor: "#CECECE",
        itemGap: 10
      },
      xAxis: {
        disableGrid: true,
        disabled: false,
        axisLine: true,
        axisLineColor: "#CCCCCC",
        calibration: false,
        fontColor: "#666666",
        fontSize: 13,
        lineHeight: 20,
        marginTop: 0,
        rotateLabel: false,
        rotateAngle: 45,
        itemCount: 5,
        boundaryGap: "center",
        splitNumber: 5,
        gridColor: "#CCCCCC",
        gridType: "solid",
        dashLength: 4,
        gridEval: 1,
        scrollShow: false,
        scrollAlign: "left",
        scrollColor: "#A6A6A6",
        scrollBackgroundColor: "#EFEBEF",
        title: "",
        titleFontSize: 13,
        titleOffsetY: 0,
        titleOffsetX: 0,
        titleFontColor: "#666666",
        format: ""
      },
      yAxis: {
        data: [
          {
            min: 0
          }
        ],
        disabled: false,
        disableGrid: false,
        splitNumber: 5,
        gridType: "solid",
        dashLength: 8,
        gridColor: "#CCCCCC",
        padding: 10,
        showTitle: false
      },
      extra: {
        column: {
          type: "group",
          width: 10, //柱状图每个柱子的图形宽度
          activeBgColor: "#000000",
          activeBgOpacity: 0.08,
          seriesGap: 0, //多series每个柱子之间的间距
          categoryGap: 0, //每个category点位（X轴点）柱子组之间的间距
          barBorderCircle: false,
          linearType: "none",
          linearOpacity: 1,
          colorStop: 0,
          meterBorder: 1,
          meterFillColor: "#FFFFFF",
          labelPosition: "outside"
        },
        tooltip: {
          showBox: true,
          showArrow: true,
          showCategory: false,
          borderWidth: 0,
          borderRadius: 0,
          borderColor: "#000000",
          borderOpacity: 0.7,
          bgColor: "#000000",
          bgOpacity: 0.7,
          gridType: "solid",
          dashLength: 4,
          gridColor: "#CCCCCC",
          boxPadding: 3,
          fontSize: 13,
          lineHeight: 20,
          fontColor: "#FFFFFF",
          legendShow: true,
          legendShape: "auto",
          splitLine: true,
          horizentalLine: false,
          xAxisLabel: false,
          yAxisLabel: false,
          labelBgColor: "#FFFFFF",
          labelBgOpacity: 0.7,
          labelFontColor: "#666666"
        },
        markLine: {
          type: "solid",
          dashLength: 4,
          data: []
        }
      }
    }
  },

  getServerData2() {

    const that = this;
    const app = getApp();
    that.setData({
      account_id: app.globalData.account_id,
    })

    wx.request({
      url: 'http://localhost:8080/report/getTrendData/' + that.data.account_id,
      // url: 'http://localhost:8080/report/getTrendData/1',
      method: 'GET',
      success: function (res) {
        // 请求成功，处理返回的数据
        console.log(res.data);
        console.log(111);
        var newRes = {
          categories: res.data.date.map(date => date.substring(0, 10)),
          series: [{
            name: "压力趋势",
            data: res.data.stress
          }]
        };
        console.log(newRes);
        this.setData({
          chartData2: JSON.parse(JSON.stringify(newRes)),
        });
        console.log(222);
        console.log(this.data.chartData2);
      }.bind(this), // 确保在这里绑定正确的上下文
      fail: function (err) {
        // 请求失败处理逻辑
        console.error('请求失败:', err);
      }
    });
  },

  // methods: {
  getServerData() {
    //模拟从服务器获取数据时的延时
    //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
    // let res = {
    //   categories: ["中立", "惊讶", "沮丧", "开心", "害怕", "厌恶", "愤怒"],
    //   series: [{
    //     name: "情绪分布",
    //     data: [90, 110, 165, 195, 187, 172, 100]
    //   }]
    // };
    // this.setData({
    //   chartData: res,
    // });


    // 发送请求到后端
    const that = this;
    const app = getApp();
    that.setData({
      account_id: app.globalData.account_id,
    })

    wx.request({
      url: 'http://localhost:8080/report/getLatestReport/' + that.data.account_id,
      // url: 'http://localhost:8080/report/getLatestReport/1',
      method: 'GET',


      success: function (res) {
        // 请求成功，处理返回的数据
        console.log(res.data);
        console.log(111);
        var newRes = {
          categories: ["中立", "惊讶", "沮丧", "开心", "害怕", "厌恶", "愤怒"],
          series: [{
            name: "情绪分布",
            data: [(res.data.neutral / 6) * 100, (res.data.surprised / 6) * 100, (res.data.sad / 6) * 100, (res.data.happy / 6) * 100, (res.data.fear / 6) * 100, (res.data.disgust / 6) * 100, (res.data.anger / 6) * 100]
          }]
        };
        console.log(newRes);
        this.setData({
          chartData: JSON.parse(JSON.stringify(newRes)),
          stress: res.data.stress,
          date: res.data.create_time.substring(0, 10)
        });
        console.log(222);
        console.log(this.data.chartData);
        console.log(this.data.date);
        console.log(333);
      }.bind(this), // 确保在这里绑定正确的上下文
      fail: function (err) {
        // 请求失败处理逻辑
        console.error('请求失败:', err);
      }
    });
  },

  getServerData3() {
    const that = this;
    const app = getApp();
    that.setData({
      account_id: app.globalData.account_id,
    })

    wx.request({

      url: 'http://localhost:8080/report/getReports/' + that.data.account_id,
      //url: 'http://localhost:8080/report/getReports/1',

      method: 'GET',

      success: (res) => {
        //请求成功，处理返回数据
        console.log(res.data);
        console.log(888);


        // 使用 forEach 来遍历 res.data 数组中的每个元素
        res.data.forEach((item, index) => {
          console.log(item.stress); // 打印每个元素的 stress 属性
          console.log(item.create_time);
          // 原始的日期时间字符串
          let dateTimeStr = item.create_time;
          // 使用正则表达式来匹配年月日部分
          let yearMonthDay = dateTimeStr.match(/^\d{4}-\d{2}-\d{2}/)[0];
          console.log(yearMonthDay); // 输出: "2024-06-04"
          // 创建一个新的对象并添加到 stressarray 中
          var ste = {
            stress: item.stress,
            date: yearMonthDay
          };
          this.data.stressarray.push(ste);
        });
        this.setData({
          stressarray: this.data.stressarray,
        });
      }
    })
  },

  getServerDataEmotion() {
    //模拟从服务器获取数据时的延时
    setTimeout(() => {
      //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
      let res = {
        series: [{
          data: [{
            "name": "中立",
            "value": 16
          }, {
            "name": "开心",
            "value": 10
          }, {
            "name": "害怕",
            "value": 15
          }, {
            "name": "沮丧",
            "value": 20
          }, {
            "name": "惊讶",
            "value": 17
          }, {
            "name": "厌恶",
            "value": 13
          }, {
            "name": "愤怒",
            "value": 17
          }]
        }]
      };
      this.setData({
        chartDataEmotion: JSON.parse(JSON.stringify(res))
      });
    }, 500);

  },

  getServerData4() {
    const that = this;
    const app = getApp();
    that.setData({
      account_id: app.globalData.account_id,
    })

    wx.request({
      url: 'http://localhost:8080/report/getEmotionData/' + that.data.account_id,
      // url: 'http://localhost:8080/report/getEmotionData/1',
      method: 'GET',


      success: function (res) {
        // 请求成功，处理返回的数据
        console.log(111111);
        console.log(res.data.data);
        console.log(res.data.data.date);
        console.log(res.data.data.emotionData);
        console.log(res.data.data.emotionData[0]);
        console.log(111111);
        var newRes = {
          categories: res.data.data.date,
          series: [
            {
              name: "中立",
              data: res.data.data.emotionData[5]
            },
            {
              name: "开心",
              data: res.data.data.emotionData[0]
            },
            {
              name: "害怕",
              data: res.data.data.emotionData[3]
            },
            {
              name: "沮丧",
              data: res.data.data.emotionData[4]
            },
            {
              name: "惊讶",
              data: res.data.data.emotionData[6]
            },
            {
              name: "厌恶",
              data: res.data.data.emotionData[2]
            },
            {
              name: "愤怒",
              data: res.data.data.emotionData[1]
            }]
        };
        console.log(newRes);
        this.setData({
          chartData4: JSON.parse(JSON.stringify(newRes))
        });
        console.log(222222);
        console.log(this.data.chartData);
        console.log(this.data.date);
        console.log(333333);
      }.bind(this), // 确保在这里绑定正确的上下文
      fail: function (err) {
        // 请求失败处理逻辑
        console.error('请求失败:', err);
      }
    });

    //模拟从服务器获取数据时的延时
    // setTimeout(() => {
    //   //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
    //   let res = {
    //       categories: ["6.17","6.18"],
          // series: [
          //   {
          //     name: "中立",
          //     data: [21,10]
          //   },
          //   {
          //     name: "开心",
          //     data: [10,14]
          //   },
          //   {
          //     name: "害怕",
          //     data: [22,13]
          //   },
          //   {
          //     name: "沮丧",
          //     data: [21,19]
          //   },
          //   {
          //     name: "惊讶",
          //     data: [12,22]
          //   },
          //   {
          //     name: "厌恶",
          //     data: [35,36]
          //   },
          //   {
          //     name: "愤怒",
          //     data: [20,16]
          //   }]
    //     };
    //   this.setData({ chartData4: JSON.parse(JSON.stringify(res)) });
    // }, 500);
  },

  onReady() {
    this.getServerData();
    this.getServerData2();
    this.getServerData3();
    this.getServerDataEmotion();
    this.getServerData4();
  },

  onShow() {
    this.getTabBar().init();
  },

  onClick(event) {

    console.log("event", event)
    this.setData({
      index: event.detail.index
    })
    let title = '';
    switch (event.detail.name) {
      case 0:
        title = '检测报告';
        break;
      case 1:
        title = '检测记录';
        break;
        // 添加更多的 case 语句来处理其他情况
      case 2:
        title = '压力趋势';
        break;
      default:
        title = `点击标签${event.detail.name}`;
    }

  },

  onClickWarn() {
    wx.showToast({
      title: `0-40为低压，41-70为中压，71-100为高压`,
      icon: 'none',
    });
  },

  // 滑动时触发的事件
  slideOn(e) {
    // 拿到当前索引并动态改变
    this.setData({
      tabsId: e.detail.current
    })
  },

  //点击tab时触发
  tabsOn(e) {
    this.setData({
      //拿到当前索引并动态改变
      tabsId: e.currentTarget.dataset.idx
    })
  },

  //日期选择对象
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
    const that = this;
    console.log('picker发送选择改变，携带值为', that.data.account_id)
    const app = getApp();
    wx.request({
      //url: 'http://localhost:8080/report/getReportByDate/1/2024-06-04',
      url: `http://localhost:8080/report/getReportByDate/${that.data.account_id}/${e.detail.value}`,
      method: 'GET',
      success: (res) => {
        console.log(777);
        console.log(res.data);
        let stressarray1 = [];
        res.data.forEach((item, index) => {
          console.log(item.stress); // 打印每个元素的 stress 属性
          console.log(item.create_time);
          // 原始的日期时间字符串
          let dateTimeStr = item.create_time;
          // 使用正则表达式来匹配年月日部分
          let yearMonthDay = dateTimeStr.match(/^\d{4}-\d{2}-\d{2}/)[0];
          console.log(yearMonthDay); // 输出: "2024-06-04"
          // 创建一个新的对象并添加到 stressarray 中
          var ste = {
            stress: item.stress,
            date: yearMonthDay
          };
          stressarray1.push(ste);
        });
        console.log(stressarray1);
        this.setData({
          stressarray: stressarray1,
          date: e.detail.value,
        });
      }
    })


  },

  showDialog() {
    Dialog.alert({
      title: '压力调整提示',
      message: '1.改善生活作息：保证足够睡眠时间规律作息；合理安排工作和休息时间；保持良好饮食和适量运动\n'+
      '2.调整心态：保持积极乐观心态，合理看待压力：尝试放松技巧，如深呼吸、冥想：寻求他人情感支持，疏导内心压力\n'+ 
      '3.建立良好习惯；养成定期运动的习惯；培养身心健康的爱好；建立良好人际关系\n 4.寻求专业铺导；必要时咨询理医生',
      selector: '#van-dialog',
      className: 'custom-dialog'
    }).then(() => {
      // on close
    });
  }
})